<template>
  <div class="payment-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>支付配置管理</span>
          <el-button type="primary" @click="handleCreate">新增配置</el-button>
        </div>
      </template>
      
      <el-table :data="configs" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="支付网关名称" />
        <el-table-column prop="app_id" label="App ID" />
        <el-table-column prop="mch_id" label="商户ID" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 支付配置表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form
        ref="configFormRef"
        :model="configForm"
        :rules="configFormRules"
        label-width="120px"
      >
        <el-form-item label="支付网关名称" prop="name">
          <el-input v-model="configForm.name" />
        </el-form-item>
        <el-form-item label="App ID" prop="app_id">
          <el-input v-model="configForm.app_id" />
        </el-form-item>
        <el-form-item label="商户ID" prop="mch_id">
          <el-input v-model="configForm.mch_id" />
        </el-form-item>
        <el-form-item label="API Key" prop="api_key">
          <el-input v-model="configForm.api_key" type="password" />
        </el-form-item>
        <el-form-item label="证书路径" prop="cert_path">
          <el-input v-model="configForm.cert_path" />
        </el-form-item>
        <el-form-item label="私钥路径" prop="key_path">
          <el-input v-model="configForm.key_path" />
        </el-form-item>
        <el-form-item label="通知URL" prop="notify_url">
          <el-input v-model="configForm.notify_url" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="configForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPaymentConfigs, createPaymentConfig, updatePaymentConfig, deletePaymentConfig, getPaymentConfigById } from '@/api/paymentConfig'

// 支付配置数据
const configs = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单引用
const configFormRef = ref()

// 支付配置表单数据
const configForm = reactive({
  id: 0,
  name: '',
  app_id: '',
  mch_id: '',
  api_key: '',
  cert_path: '',
  key_path: '',
  notify_url: '',
  status: 1
})

// 表单验证规则
const configFormRules = {
  name: [
    { required: true, message: '请输入支付网关名称', trigger: 'blur' }
  ],
  app_id: [
    { required: true, message: '请输入App ID', trigger: 'blur' }
  ],
  mch_id: [
    { required: true, message: '请输入商户ID', trigger: 'blur' }
  ],
  api_key: [
    { required: true, message: '请输入API Key', trigger: 'blur' }
  ]
}

// 获取支付配置列表
const fetchConfigs = async () => {
  loading.value = true
  try {
    const res: any = await getPaymentConfigs()
    
    if (res.success) {
      configs.value = res.data
    } else {
      ElMessage.error(res.message || '获取支付配置列表失败')
    }
  } catch (error) {
    ElMessage.error('获取支付配置列表失败')
  } finally {
    loading.value = false
  }
}

// 处理新增
const handleCreate = () => {
  dialogTitle.value = '新增支付配置'
  isEdit.value = false
  // 重置表单
  Object.assign(configForm, {
    id: 0,
    name: '',
    app_id: '',
    mch_id: '',
    api_key: '',
    cert_path: '',
    key_path: '',
    notify_url: '',
    status: 1
  })
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = async (row: any) => {
  dialogTitle.value = '编辑支付配置'
  isEdit.value = true
  // 获取详细信息
  try {
    const res: any = await getPaymentConfigById(row.id)
    if (res.success) {
      Object.assign(configForm, res.data)
      dialogVisible.value = true
    } else {
      ElMessage.error(res.message || '获取支付配置详情失败')
    }
  } catch (error) {
    ElMessage.error('获取支付配置详情失败')
  }
}

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除支付配置 "${row.name}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res: any = await deletePaymentConfig(row.id)
      if (res.success) {
        ElMessage.success('删除成功')
        fetchConfigs()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 提交表单
const submitForm = async () => {
  if (!configFormRef.value) return
  
  await configFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        let res: any
        if (isEdit.value) {
          // 编辑
          const { id, ...updateData } = configForm
          res = await updatePaymentConfig(id, updateData)
        } else {
          // 新增
          res = await createPaymentConfig(configForm)
        }
        
        if (res.success) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          dialogVisible.value = false
          fetchConfigs()
        } else {
          ElMessage.error(res.message || (isEdit.value ? '更新失败' : '创建失败'))
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      }
    }
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchConfigs()
})
</script>

<style scoped>
.payment-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>